<?php

namespace common\observer;

use common\model\StepModel;
use common\model\TaskModel;
use common\model\UserModel;
use support\SingletonTrait;
use common\model\EntityModel;
use common\service\OptionsService;
use common\service\TaskMemberService;
use teamones\dbeventObserver\interfaces\SplSubject;
use teamones\dbeventObserver\interfaces\SplObserver;

/**
 * 贴图任务待办执行人同步观察者
 */
class TexStepTodoTaskMemberExecutorSync implements SplObserver
{
    use SingletonTrait;

    /**
     * @inheritDoc
     * @throws \Throwable
     * @throws \think\Exception
     */
    function update(SplSubject $subject): void
    {
        $updateData = $subject->getSplUpdateData();
        if (!isset($updateData['executor'])) {
            return;
        }
        $newExecutor = $subject->getSplNewData()['executor'];
//        $oldExecutor = $subject->getOldData()['executor'];

        $task = $subject->getSubjectData();
        $stepCode = model(StepModel::class)->where(['id' => $task['step_id']])->value('code');

        if (!in_array($stepCode, OptionsService::getInstance()->getTexStepCode())) {
            return;
        }
        $entityModuleCode = module_by_id($task['entity_module_id'])['code'];
        $entityTodoTaskField = $entityModuleCode . '_task';
        $entity = model(EntityModel::class)->alias($entityModuleCode)
            ->where(['id' => $task['entity_id']])
            ->field("json->>'$.{$entityTodoTaskField}' as $entityTodoTaskField,created_by")
            ->find();
        $entityTodoTaskIdList = array_filter(explode(',', $entity[$entityTodoTaskField]));
        if (empty($entityTodoTaskIdList)) {
            return;
        }
        $entityTodoTaskIdList = model(TaskModel::class)->where(['id' => ['IN', $entityTodoTaskIdList]])->column('id');
        $entityCreatedByUnionId = model(UserModel::class)->where(['id' => $entity['created_by']])->value('union_id');
        $data = [
            'task' => [
                'step_type' => TaskModel::STEP_TYPE_ENTITY_TO_DO,
            ],
            'partner' => [],
        ];
        if ($entityCreatedByUnionId > 0) {
            $data['partner'][] = $entityCreatedByUnionId;
        }
        if ($newExecutor > 0) {
            $newExecutorUnionId = model(UserModel::class)->where(['id' => $newExecutor])->value('union_id');
            $data['executor'] = [$newExecutorUnionId];
        }
        foreach ($entityTodoTaskIdList as $entityTodoTaskId) {
            // 清单创建人是参与人 执行人是工序任务执行人
            $data['task']['id'] = $entityTodoTaskId;
            TaskMemberService::getInstance()->updateTask($data, \request()->getUserId());
        }
    }

}
